import React, { useState, useEffect, useRef, useMemo } from 'react'
import {
  Button,
  Divider,
  Space,
  Breadcrumb,
  Select,
  Image,
  Tooltip,
  message,
} from 'antd'
import { getTaskDetail } from '@/api/url'
import { useLocation, useNavigate } from 'react-router-dom'
import Layout from './Layout'
import { RadialBar } from '@ant-design/plots'
import { LeftOutlined, RightOutlined } from '@ant-design/icons'
// import ReactPlayer from 'react-player'
import AudioPlayer from 'react-h5-audio-player'
import {
  reinforceMap,
  apply_sceneMap,
  imgPathMap,
  audioPathMap,
  numTransform,
} from './utils/statusMap'
import Slider from 'react-slick'
import 'react-h5-audio-player/lib/styles.css'
import styles from './taskDetail.module.scss'
import 'slick-carousel/slick/slick.css'
import 'slick-carousel/slick/slick-theme.css'

let urlType
let urlTypeRes
const TaskDetail = () => {
  const location = useLocation()
  const navigate = useNavigate()
  const [taskInfo, setTaskInfo] = useState(null)
  const [reinforceResult, setReinforceResult] = useState(null) //所有加固方法的数据
  const [urlList, setUrlList] = useState(null) //加固案例的url
  const [curUrl, setCurUrl] = useState([])
  const sliderRef = useRef(null)

  useEffect(() => {
    getTaskInfo()
  }, [])

  //获取页面数据
  const getTaskInfo = () => {
    getTaskDetail({ id: location.state.id })
      .then((res) => {
        setTaskInfo(res.data)
      })
      .catch((err) => {
        console.log(err)
      })
  }

  const getUrlType = (res) => {
    // audio_path   imgPath
    if (res?.audio_path) {
      return 'audio_path'
    }
    if (res?.imgPath) {
      return 'imgPath'
    }
    if (res?.text) {
      return 'text'
    }
    return ''
  }

  const changOpt = (val) => {
    setReinforceResult(taskInfo?.reinforce_result[val])
    setUrlList(taskInfo?.reinforce_result[val].res)
    urlType = getUrlType(taskInfo?.reinforce_result[val].res[0])

    if (urlType === 'audio_path') {
      urlTypeRes = urlType.replace('path', 'res')
    }
    if (urlType === 'imgPath') {
      urlTypeRes = urlType.replace('Path', '_predict_res')
    }
    setCurUrl(
      taskInfo?.reinforce_result[val].res?.map((item) => {
        return [item[urlType], item[urlTypeRes], '原始样本']
      })
    )
  }

  const selectOpt = useMemo(() => {
    changOpt(taskInfo?.reinforce_way[0])
    console.log('ffffffff!!!!!!!!!!!fffff', taskInfo?.reinforce_way)
    //默认选项
    return taskInfo?.reinforce_way.map((item) => {
      return {
        label: reinforceMap.find((i) => i.method_name === item).name,
        value: item,
      }
    })
  }, [taskInfo])

  //饼图数据
  const data = useMemo(() => {
    return [
      {
        type: '攻击成功量',
        value: reinforceResult?.adv_success,
      },
      {
        type: '防御成功量',
        value: reinforceResult?.def_success,
      },
      {
        type: '样本总量',
        value: reinforceResult?.all_total,
      },
    ]
  }, [reinforceResult])

  const config = useMemo(() => {
    return {
      appendPadding: 10,
      angleField: 'value',
      colorField: 'type',
      radius: 0.9,
      legend: {
        layout: 'vertical',
        position: 'right',
      },
      data,
      xField: 'type',
      yField: 'value',
      radius: 0.8,
      innerRadius: 0.2,
      color: ({ type }) => {
        switch (type) {
          case '样本总量':
            return '#5B8FF9'
          case '防御成功量':
            return '#65789B'
          case '攻击成功量':
            return '#61DDAA'
          default:
            break
        }
      },
    }
  }, [reinforceResult])

  const toLeft = () => {
    sliderRef.current.slickPrev()
  }

  const toRight = () => {
    sliderRef.current.slickNext()
  }

  //轮播图
  const settings = {
    dots: false,
    infinite: false,
    slidesToShow: 3,
    slidesToScroll: 3,
  }

  return (
    <Layout>
      <Breadcrumb
        key="outer"
        items={[
          {
            title: <a href="/taskList">测评任务管理</a>,
          },
          {
            title: '查看测评报告',
          },
        ]}
      />

      <div>
        <div className={styles.taskTitle}>{taskInfo?.name}</div>
        <div className={styles.taskInfo}>
          <span style={{ marginLeft: 50 }}>应用场景：</span>
          <span>{apply_sceneMap[taskInfo?.apply_scene]}</span>
          <span style={{ marginLeft: 300 }}>测评完成时间：</span>
          <span>{taskInfo?.completion_time}</span>
        </div>
      </div>

      <Divider />
      <Space
        direction="vertical"
        size="middle"
        style={{
          display: 'flex',
        }}
      >
        <div className={styles.taskTitle}>加固概览</div>
        <div>
          <span className={styles.subTitle}>加固方法：</span>
          {taskInfo ? (
            <Select
              style={{ width: '40%', marginLeft: 20 }}
              placeholder="请选择"
              onChange={(val) => changOpt(val)}
              options={selectOpt}
              defaultValue={taskInfo.reinforce_way[0]}
            />
          ) : null}
        </div>

        <div>
          <span className={styles.subTitle}>加固成功率：</span>
          <span className={styles.socre}>
            <b>{Number(reinforceResult?.reinforce_success_rate).toFixed(2)}%</b>
          </span>
        </div>

        <section className={styles.section}>
          {/* 饼图 */}
          <div className={styles.leftPart}>
            <span className={styles.subTitle} style={{ marginBottom: 20 }}>
              样本数量展示：
            </span>
            <RadialBar {...config} />
          </div>
          <div className={styles.rightPart}>
            <span
              className={styles.subTitle}
              style={{ marginBottom: 20, textAlign: 'left' }}
            >
              加固案例：
            </span>
            <Slider
              ref={sliderRef}
              {...settings}
              className={styles.sampleContent}
            >
              {urlList?.map((item, index) => {
                return (
                  <div
                    style={{ padding: 10, boxSizing: 'border-box' }}
                    key={index}
                  >
                    <div className={styles.sampleCard}>
                      <div className={styles.imageCard}>
                        {urlType === 'imgPath' ? (
                          <Image
                            style={{
                              // maxHeight: '154px',
                              height: '154px',
                              maxWidth: '100%',
                              // aspectRatio: '154/86',
                              borderRadius: 6,
                              border: '1px solid rgba(29, 29, 53, 0.15)',
                              boxShadow: '0px -1px 0 0 #e8e8e8 inset',
                            }}
                            src={curUrl[index][0]}
                          />
                        ) : null}
                        {/*  <ReactPlayer
                            width='100%'
                            height='100%'
                            volume={0.6}
                            muted
                            pip
                            controls
                            playing={playing}
                            onClick={() => {
                              setPlaying(true)
                              console.log(playing)
                            }}
                          url='https://zhstatic.zhihu.com/cfe/griffith/zhihu2018_hd.mp4'
                          // url={'http://172.18.1.214:9000'+`/data/reinforce/data/audio/AudioTurbulence/adv/3528-168669-0073.wav`}
                          /> */}
                        {urlType === 'audio_path' ? (
                          <AudioPlayer
                            autoPlay={false}
                            src={curUrl[index][0]}
                            onPlay={(e) => console.log('onPlay')}
                            showJumpControls={false}
                            showFilledVolume={true}
                            autoPlayAfterSrcChange={false}
                            layout="stacked-reverse"
                            className={'audioPlayer'}
                          />
                        ) : null}
                      </div>
                      <p style={{ textAlign: 'center' }}>
                        {'案例' +
                          numTransform[index + 1] +
                          '：' +
                          curUrl[index][2]}
                      </p>
                      <Select
                        style={{ width: '100%' }}
                        defaultValue={{
                          value: '0',
                          label: '原始样本',
                        }}
                        labelInValue
                        onSelect={(val) => {
                          if (urlType === 'audio_path') {
                            curUrl[index] = [
                              item[audioPathMap[val.value][0]],
                              item[audioPathMap[val.value][1]],
                              audioPathMap[val.value][2],
                            ]
                            setCurUrl([...curUrl])
                          }

                          if (urlType === 'imgPath') {
                            curUrl[index] = [
                              item[imgPathMap[val.value][0]],
                              item[imgPathMap[val.value][1]],
                              imgPathMap[val.value][2],
                            ]
                            setCurUrl([...curUrl])
                          }
                        }}
                        options={[
                          {
                            value: '0',
                            label: '原始样本',
                          },
                          {
                            value: '1',
                            label: '加固样本',
                          },
                          {
                            value: '2',
                            label: '对抗样本',
                          },
                        ]}
                      />
                      <p className={styles.boldFont}>分类结果Top5：</p>

                      {[...curUrl[index][1]].map((item, idx) => {
                        if (idx % 3 == 0) {
                          return (
                            <div className={styles.reInforceCase} key={idx}>
                              <Tooltip title={curUrl[index][1][0]}>
                                <p className={styles.reInforceCaseName}>
                                  {curUrl[index][1][0]}
                                </p>
                              </Tooltip>
                              <p className={styles.boldFont}>
                                {urlType === 'audio_path'
                                  ? Number(curUrl[index][1][2] * 100).toFixed(
                                      1
                                    ) + '%'
                                  : Number(curUrl[index][1][2]).toFixed(1) +
                                    '%'}
                              </p>
                            </div>
                          )
                        }
                      })}
                    </div>
                  </div>
                )
              })}
            </Slider>

            <div className={styles.leftBtn} onClick={() => toLeft()}>
              <LeftOutlined />
            </div>
            <div className={styles.rightBtn} onClick={() => toRight()}>
              <RightOutlined />
            </div>
          </div>
        </section>
      </Space>

      <div style={{ marginTop: 50, bottom: 100, textAlign: 'center' }}>
        <Button onClick={() => navigate('/taskList')} type="primary">
          返回
        </Button>
      </div>
    </Layout>
  )
}

export default TaskDetail
